<template>
	<view class="pick-video">
		<view class="page1" v-if="pageTabbarAc == 0">
			<view class="main-tabbar">
				<view :class="['tabbar-item-1', tabbarAc == item.id ? 'ac' : '']" v-for="(item, index) in tabbarList" @click="changeTabbarAc({ item, index })" :key="item.id">
					<view class="text">{{ item.text }}</view>
				</view>
			</view>
			<view class="main-tabbar" v-if="tabbarAc == 1">
				<view :class="['tabbar-item', tabbarAc2 == item.id ? 'ac' : '']" v-for="(item, index) in tabbarList2" :key="item.id" @click="changeTabbarAc2({ item, index })">
					<view class="text">{{ item.classifyName }}</view>
				</view>
			</view>
			<view class="main-content">
				<scroll-view class="scroll_view" scroll-y style="width: 100%" @scrolltolower="contentListScroll">
					<view :class="['contentList', chicunAc == 1 ? 'style2' : '']" v-if="tabbarAc == 1" ref="videoContentList">
						<template v-if="yushe.length">
							<view class="contentItem" v-for="(item, index) in yushe" @tap="pickContentItem({ item, index })" :key="item.id">
								<image class="pic" :src="pageItem.ac == 5 ? item.theCover : ''" mode="widthFix"></image>
								<video class="vid" v-if="item.playShow" :src="pageItem.ac == 5 ? item.matterUrl : ''" :controls="true" @tap.stop=""></video>
								<view class="bottom">
									<view class="name">{{ item.matterName }}</view>
								</view>
								<!-- #ifndef APP -->
								<view class="tag" @tap.stop="changePlayShow(item, index, 'yushe')">
									{{ item.playShow ? '取消浏览' : '浏览' }}
								</view>
								<!-- #endif -->
							</view>
						</template>
					</view>
					<view class="contentList-kong" v-if="tabbarAc == 1 && !yushe.length">
						<view class="text">暂无数据</view>
					</view>
					<view class="contentList" v-if="tabbarAc == 2" ref="videoContentList">
						<view class="contentItem" :style="{ '--height-val': 'calc(30vh - 9vw)' }" @click="addContentItem()">
							<image class="pic add" :src="imgPath + 'createAvatar/changjing-add.svg'" mode="widthFix"></image>
							<view class="bottom">
								<view class="name">{{ '本地上传' }}</view>
							</view>
						</view>
						<view
							class="contentItem"
							v-for="(item, index) in geren"
							@tap="pickContentItem({ item, index })"
							:key="item.id"
							:style="{ '--height-val': 'calc(30vh - 9vw)' }"
						>
							<image class="pic" :src="pageItem.ac == 5 ? item.picSrc : ''" mode="widthFix"></image>
							<video class="vid" v-if="item.playShow" :src="pageItem.ac == 5 ? item.matterUrl : ''" :controls="true" @tap.stop=""></video>
							<view class="bottom">
								<view class="name">{{ item.matterName }}</view>
							</view>
							<!-- #ifndef APP -->
							<view class="tag" @tap.stop="changePlayShow(item, index, 'geren')">
								{{ item.playShow ? '取消预览' : '预览' }}
							</view>
							<!-- #endif -->
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="page2" v-if="pageTabbarAc == 1">
			<view class="main-edit">
				<view class="btns">
					<view class="btn-item" @tap="del()">
						<image class="icon" :src="imgPath + 'createAvatar/del.svg'" mode=""></image>
						<view class="text">删除</view>
					</view>
					<view class="btn-item" @tap="changeZIndex(1)">
						<image class="icon" :src="imgPath + 'createAvatar/up.svg'" mode=""></image>
						<view class="text">层级上移</view>
					</view>
					<view class="btn-item" @tap="changeZIndex(-1)">
						<image class="icon" :src="imgPath + 'createAvatar/up.svg'" mode="" style="transform: rotate(180deg)"></image>
						<view class="text">层级下移</view>
					</view>
				</view>
			</view>
			<view class="textStyle-item">
				<view class="label">音量</view>
				<view class="r-c slider-box">
					<slider :value="volume" @change="changeElVolume" step="1" :min="0" :max="100" show-value />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import * as api from '@/api/createVideo.js';
import axios from 'axios';
let timer = null;
import { tools } from '../../../../utils/util';
export default {
	props: {
		show: {
			type: Boolean,
			default: false
		},
		promiseRes: {
			type: Object | Function,
			default() {
				return null;
			}
		},
		currInd: {
			type: Number,
			default: -1
		},
		scene2: {
			type: Array,
			default() {
				return [];
			}
		},
		pageItem: {
			type: Object,
			default() {
				return {};
			}
		},
		chicunAc: {
			type: Number,
			default: 2
		},
		chicunList: {
			type: Array,
			default() {
				return [];
			}
		}
	},
	data() {
		return {
			imgPath: tools.imgPath,
			pageTabbarAc: 0,
			pageTabbarList: [],
			tabbarAc: 1,
			tabbarList: [],
			tabbarAc2: null,
			tabbarList2: [],
			yushe: [],
			yusheCurrent: 1,
			yusheSize: 21,
			yusheTotal: null,
			geren: [],
			gerenCurrent: 1,
			gerenSize: 21,
			gerenTotal: null,
			uploadFileSize: 200,
			contentList: [],
			volume: 0
		};
	},
	async created() {
		this.initPageTabbarList();
		this.initTabbarList();
		let next = await this.initGetData();
		if (this.promiseRes) {
			this.promiseRes(true);
		}
	},
	methods: {
		// 本地上传
		addContentItem() {
			const that = this;
			let extension = ['avi', 'mp4', '.mkv', 'mov', 'flv', 'rmvb', '3gp'];
			// uni.chooseFile({
			// uni.chooseMessageFile({
			// 	count: 1, //默认100
			// 	extension: extension,
			uni.chooseVideo({
				sourceType: ['album', 'camera'],
				maxDuration: 30,
				compressed: false,
				camera: 'front',
				success: async (res) => {
					const tempFilePaths = res.tempFilePaths;
					let file = res.tempFiles[0];
					// if (!file.type.includes("video")) {
					// 	return tools.easyToast("请选择视频频文件！");
					// }
					let name = file.name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9\.]/g, '');
					// if (!/^[\u4e00-\u9fa5a-zA-Z0-9\.\-]+$/.test(name)) {
					// 	return tools.easyToast("文件名不能包含符号，只能是文字或数字");
					// }
					if (file.size / 1024 / 1024 > this.uploadFileSize) {
						return tools.easyToast(`文件大小超过${this.uploadFileSize}M!`);
					}
					uni.showLoading({
						title: '上传中'
					});
					let ossData = await api.postOSS({
						reqType: 'mat_video',
						matName: name,
						payLoad: {}
					});
					let ress = await that.wx_getOSSApi_new(ossData, file.path, name);
					if (!ress) return;
					that.geren = [];
					that.getDataApi2();
				},
				fail(err) {
					console.log(err);
				}
			});
		},
		// wx小程序oss上传文件
		wx_getOSSApi_new(ossData, file, name) {
			const that = this;
			let res = ossData;
			function getUUID() {
				let keyStr = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
				keyStr = 'xxxxxxxx-6xxx';
				return keyStr.replace(/[xy]/g, (c) => {
					return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
				});
			}
			let url_name = 'https://alleymall.oss-cn-guangzhou.aliyuncs.com';
			let key = res.data.dir + '/' + getUUID() + name;
			return new Promise((next) => {
				uni.uploadFile({
					url: url_name,
					filePath: file,
					name: 'file',
					formData: {
						policy: res.data.policy,
						signature: res.data.signature,
						ossaccessKeyId: res.data.accessid,
						key: key,
						dir: res.data.dir,
						host: res.data.host,
						expire: res.data.expire,
						callback: res.data.callback
					},
					success: (uploadFileRes) => {
						let src = url_name + '/' + key;
						// console.log(src);
						// that.audioPlayerSrc = src;
						// console.log(response);
						next({ ...uploadFileRes, src });
					},
					fail(err) {
						console.log(err);
						next(false);
					}
				});
			});
		},

		//上传文件api
		async getOSSApi_new(ossData, file, name) {
			const that = this;
			let res = ossData;

			function getUUID() {
				let keyStr = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
				keyStr = 'xxxxxxxx-6xxx';
				return keyStr.replace(/[xy]/g, (c) => {
					return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
				});
			}
			const formData = new FormData();
			let url_name = 'https://alleymall.oss-cn-guangzhou.aliyuncs.com';
			let key = res.data.dir + '/' + getUUID() + name;
			formData.append('policy', res.data.policy);
			formData.append('signature', res.data.signature);
			formData.append('ossaccessKeyId', res.data.accessid);
			formData.append('key', key);
			formData.append('dir', res.data.dir);
			formData.append('host', res.data.host);
			formData.append('expire', res.data.expire);
			formData.append('callback', res.data.callback);
			// formData.append('type', res.data.callback)
			formData.append('file', file);

			return axios
				.post(url_name, formData, {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				})
				.then((response) => {
					let src = url_name + '/' + key;
					// console.log(src);
					// that.audioPlayerSrc = src;
					// console.log(response);
					return {
						...response,
						src
					};
				})
				.catch((error) => {
					console.log(error);
				});
		},
		// 修改浏览状态
		changePlayShow(item, index, field) {
			// console.log("修改浏览状态", item, index, field, this[field]);
			let playShow = !item.playShow;
			this[field].map((e) => {
				this.$set(e, 'playShow', false);
			});
			this[field][index].playShow = playShow;
		},
		// 滚动事件(做懒加载)
		contentListScroll(event) {
			const that = this;
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => {
				if (that.tabbarAc == 1) {
					if (this.yusheTotal === this.yushe.length) return;
					this.yusheCurrent++;
					this.getDataApi();
				} else {
					if (this.gerenTotal === this.geren.length) return;
					this.gerenCurrent++;
					this.getDataApi2();
				}
				clearTimeout(timer);
				timer = null;
			}, 300);
		},
		// 获取公共数据分类api
		async getSysmatTwoType() {
			const type = 'video';
			let res = await api.getSysmatTwoType(type);
			if (!res) return;
			this.tabbarList2 = [
				{
					id: null,
					classifyName: '全部'
				},
				...res.data
			];
			this.tabbarAc2 = this.tabbarList2[0].id;
			return true;
		},
		// 获取公共数据api
		async getDataApi(_id) {
			_id = ['Null', 'Number', 'String'].includes(tools.myTypeOf(_id)) ? _id : this.tabbarAc2;
			let res = null;
			if (_id) {
				//获取分类数据
				let data = {
					oneid: _id,
					size: this.yusheSize,
					current: this.yusheCurrent,
					twoid: this.chicunAc //横屏1，竖屏2
				};
				res = await api.getVideoSysmat(data);
			} else {
				//获取全部数据
				let data = {
					type: 'video',
					size: this.yusheSize,
					current: this.yusheCurrent,
					id: this.chicunAc //横屏1，竖屏2
				};
				res = await api.getVideoSysmatAll(data);
			}
			if (!res?.data?.records) {
				this.yushe = [];
				this.yusheTotal = null;
				return;
			}
			this.yusheTotal = res.data.total;
			let yushe = res.data.records.map((e) => ({
				...e,
				volume: this.volume,
				picSrc: e.theCover,
				playShow: false
			}));
			this.yushe = [...this.yushe, ...yushe];
			return true;
		},
		// 获取私有数据api
		async getDataApi2() {
			let res = await api.getUserSource('video');
			if (!res) return;
			this.geren = res.data.map((e) => ({
				...e,
				volume: this.volume,
				picSrc: e.matterUrl + `?x-oss-process=video/snapshot,t_${0},f_png,m_fast`,
				playShow: false
			}));
			return true;
		},
		// 获取后端数据
		async initGetData() {
			let getData = new Promise(async (next) => {
				let flag = await this.getSysmatTwoType();
				if (!flag) return;
				let flag2 = await this.getDataApi();
				if (!flag2) return;
				next(true);
			});
			await Promise.all([getData]);
			return true;
		},
		// 初始化contentList
		initContentList() {
			this.contentList = matData.map((e) => ({
				...e,
				picSrc: e.theCover
			}));
		},
		// 初始化tabbarList
		initTabbarList() {
			this.tabbarList = [
				{
					text: '预设',
					id: 1
				},
				{
					text: '本地',
					id: 2
				}
			];
		},
		//初始化pageTabbarList
		initPageTabbarList() {
			this.pageTabbarList = [
				{
					text: '选择图片',
					id: 0
				},
				{
					text: '编辑图片',
					id: 1
				}
			];
			if (this.pageItem) {
				// console.log('初始化pageTabbarList',this.pageItem);
				this.pageTabbarAc = this.pageItem.pageAc;
			}
		},
		//切换页面类型
		changePageTabbarAc({ item, index }) {
			// if (this.pageTabbarAc == item.id) return;
			this.pageTabbarAc = item.id;
			if (this.pageTabbarAc == 0) {
				this.$emit('changeMyDH', 35);
			} else {
				this.$emit('changeMyDH', 16);
			}
		},
		// 切换类型
		changeTabbarAc({ item, index }) {
			this.tabbarAc = item.id;
			if (this.tabbarAc == 2) {
				//获取私有数据
				this.getDataApi2();
			}
		},
		//切换数据子类型
		changeTabbarAc2({ item, index }) {
			this.tabbarAc2 = item.id;
			this.yushe = [];
			this.yusheCurrent = 1;
			this.yusheTotal = null;
			this.getDataApi();
		},
		//选择item
		pickContentItem({ item, index }) {
			this.$emit('pickVideo', {
				item,
				index
			});
		},
		// 删除
		del() {
			this.$emit('removeEl', this.currInd);
		},
		// 修改层级
		changeZIndex(num) {
			if (this.currInd == null || this.currInd < 0) {
				return tools.easyToast('请先选择图片!');
				// if (index == -1) {
				// 	tools.easyToast('请先选择数字人!');
				// } else {
				// 	this.$emit('changeZIndex', this.currInd, num);
				// };
			} else {
				this.$emit('changeZIndex', this.currInd, num);
			}
		},
		// 修改视频音量
		changeElVolume(e) {
			this.volume = e.detail.value;
			this.$emit('changeElVolume', this.currInd, this.volume);
		}
	},
	watch: {
		['pageItem.ac'](val) {
			if (val != 5) return;
			this.changePageTabbarAc({
				item: {
					id: this.pageItem.pageAc
				}
			});
		},
		show(val) {
			if (val) {
				if (this.pageItem.ac != 5) return;
				this.yushe = [];
				this.yusheCurrent = 1;
				this.yusheTotal = null;
				this.getDataApi();
			}
		}
	}
};
</script>

<style lang="scss">
.pick-video {
	display: flex;
	flex-direction: column;
	overflow: hidden;
	height: 100%;

	.page1 {
		display: flex;
		flex-direction: column;
		overflow: hidden;
		height: 100%;
	}

	.main-tabbar {
		display: -webkit-box;
		overflow: auto;

		.tabbar-item-1 {
			padding: 2vw;
			font-size: 32rpx;
			font-weight: 400;
			color: rgba(255, 255, 255, 1);
			display: flex;
			justify-content: center;
			align-items: center;

			&.ac {
				.text {
					color: rgba(0, 153, 127, 1);
					border-bottom: 2px solid rgba(243, 173, 51, 1);
				}
			}

			.text {
				padding-bottom: 2vw;
			}
		}

		.tabbar-item {
			padding: 0.5vw 1vw;
			color: rgba(255, 255, 255, 0.36);
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 100vw;
			background: rgba(255, 255, 255, 0.125);
			margin: 0vw 5vw 2vw 0vw;
			min-width: 10vw;

			&.ac {
				border: 2px solid rgba(0, 153, 127, 1);

				.text {
					color: rgba(0, 153, 127, 1);
					font-weight: 700;
				}
			}

			.text {
				font-size: 24rpx;
				font-weight: 400;
			}
		}
	}

	.main-content {
		flex: 1;
		overflow: hidden;
		display: flex;
		--height-val: calc(30vh - 22vw);
		.scroll_view {
			width: 100%;
			height: 68vh;
			display: flex;
			overflow: hidden;
		}
		.contentList {
			flex: 1;
			width: 100%;
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 2vw;
			text-align: center;
			overflow: hidden;
			&.style2 {
				grid-template-columns: repeat(2, 1fr);
			}
			.contentItem {
				width: 100%;
				overflow: hidden;
				margin-right: 3vw;
				margin-bottom: 1.2vw;
				border-radius: 2vw;
				background: rgba(28, 43, 46, 1);
				display: flex;
				justify-content: center;
				align-items: center;
				position: relative;
				&.first {
					width: 30vw;
				}
				.pic {
					width: 100%;
					height: 100%;
					&.add {
						width: 30%;
						height: 30%;
					}
				}

				.vid {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
				}

				.tag {
					position: absolute;
					top: 2vw;
					right: 2vw;
					border-radius: 3vw 3vw 3vw 3vw;
					background: linear-gradient(270deg, rgba(0, 222, 185, 1) 0%, rgba(122, 255, 233, 1) 100%);
					font-size: 20rpx;
					font-weight: 400;
					color: rgba(22, 24, 30, 1);
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 1vw 1.5vw;
				}

				.bottom {
					position: absolute;
					bottom: 0vw;
					width: 100%;
					height: 6vw;
					display: flex;
					justify-content: center;
					align-items: center;
					background: rgba(22, 24, 30, 0.7);
					font-size: 20rpx;
					font-weight: 400;
					color: rgba(204, 204, 204, 1);
				}
			}
		}
		.contentList-kong {
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.page2 {
		.main-edit {
			.btns {
				display: flex;

				.btn-item {
					border: 1px solid #fff;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					min-width: 20vw;
					margin-right: 2vw;
					border-radius: 2vw;
					padding: 1vw;

					.icon {
						width: 5vw;
						height: 5vw;
						display: block;
					}
				}
			}
		}

		.textStyle-item {
			width: 100%;
			display: flex;
			align-items: center;
			padding: 2vw 0vw;

			.label {
			}

			.r-c {
				margin-left: 3vw;
				flex: 1;

				&.slider-box {
				}
			}
		}
	}
}
</style>
